import { splitLyricsString } from '../../utils/common';
import { hasEnded } from '../../utils/progressbar';
import { LOAD_SONG, OPEN_SONG_PAGE, CLOSE_SONG_PAGE, SHOW_LYRICS, CTRL_SONG, GET_URL_SYNC, TOGGLE_LYRICS } from '../actions/music.action';
let initialState = {
    showSongPage: false,
    curSong: {
        id: '',
        url: '',
        lrc: '',
        audio: null
    },
    isPlaying: true,
    toggleLyrics: false,
    playRecord: {}
};

export default (state = initialState, action) => {
    switch (action.type) {
        case LOAD_SONG:
            let curSong = action.item;
            curSong.url = action.meta.url;
            curSong.lrc = splitLyricsString(action.meta.lrc.lyric);
            if (state.curSong.audio) {
                state.curSong.audio.pause();
                if (!state.playRecord[state.curSong.id]) state.playRecord[state.curSong.id] = state.curSong;
            }
            curSong.audio = new window.Audio(action.meta.url);
            curSong.audio.play();
            
            let newState = {
                ...state,
                curSong,
                playRecord: JSON.parse(JSON.stringify(state.playRecord))
            }
            console.log('LOAD_SONG', newState);
            return newState;
        case OPEN_SONG_PAGE:
            return {
                ...state,
                showSongPage: true
            }
        case CLOSE_SONG_PAGE:
            return {
                ...state,
                showSongPage: false
            }
        case SHOW_LYRICS: {
            let curSong = JSON.parse(JSON.stringify(state.curSong));
            curSong.lrc = action.lrc;
            return {
                ...state,
                curSong
            }
        }
        case CTRL_SONG: {
            let curAudio = state.curSong.audio;
            if (!curAudio) return state;
            if (curAudio.paused) {
                // When song is not end or loop is activated, the music can go and play!
                if (!hasEnded(curAudio) || curAudio.loop) curAudio.play();
            } else {
                curAudio.pause();
            }
            return {
                ...state,
                isPlaying: action.bool
            }
        }
        case GET_URL_SYNC: { 
            console.log('GET_URL_SYNC', action);
            let audio = state.audio;
            if (!audio) {
                audio = new window.Audio(action.url);
            }
            return {
                ...state,
                audio
            }
        }
        case TOGGLE_LYRICS: {
            return {
                ...state,
                toggleLyrics: action.bool
            }
        }
        default:
            return state;
    }
}